package com.qf.common.core.sentinel;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;

import java.util.List;

@Slf4j
public class SentinelConfigInit implements CommandLineRunner {

    @Value("${spring.application.name}")
    private String appName;
    @Value("${spring.cloud.nacos.server-addr}")
    private String nacosAddr;


    @Override
    public void run(String... args) throws Exception {
        log.debug("[sentinel-nacos-config] - 读取nacos中sentinel的限制规则 - {}", appName);

        /**
         * 从nacos中根据微服务的名字加载流控规则
         * nacos -> text(json/yaml/properties) -> List<FlowRule>
         */
        ReadableDataSource<String, List<FlowRule>> nacosDataSource = new NacosDataSource<>(
                nacosAddr,
                "SENTINEL_GROUP",
                appName + "-flow-rule",
                json -> JSON.parseObject(json, new TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(nacosDataSource.getProperty());


        /**
         * 从nacos中根据微服务的名字加载降级规则
         */
        ReadableDataSource<String, List<DegradeRule>> nacosDataSource2 = new NacosDataSource<>(
                nacosAddr,
                "SENTINEL_GROUP",
                appName + "-degrade-rule",
                json -> JSON.parseObject(json, new TypeReference<List<DegradeRule>>() {
                }));
        DegradeRuleManager.register2Property(nacosDataSource2.getProperty());
    }
}
